import { createRouter, createWebHistory } from 'vue-router'
import role from "./model/role"
import organization from "./model/organization"
import staffRouter from "./model/staff"
import authority from "./model/authority"
import attendance from "./model/attendance"
import examine from "./model/examine"
import wage from "./model/wage"
import social from "./model/social"
import { StoreUsers } from "@/stores"
import { registerRoutes } from "./reouterList.js"


import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 1000, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 更改启动时使用的最小百分比
  parent: 'body', //指定进度条的父容器
})

export let routerArray = [
  {
    path: "/home",
    name: "home",
    component: () => import("@/views/home/home.vue"),
    meta: {
      title: "首页",
      icon: 'Dashboard (1)'
    },
  },
  organization,
  role,
  staffRouter,
  authority,
  attendance,
  examine,
  wage,
  social
]

// 静态路由
export let rou: any = [
  {
    path: '/',
    name: '/',
    component: () => import('../views/Layout/index.vue'),
    meta: {
      title: "首页",
      icon: 'Dashboard (1)'
    },
    redirect: "/home",
    children: routerArray
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue")
  },
  {
    path: "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("@/views/404/404.vue")
  }
]
// 创建路由
export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: rou
})
// 防止路由无限循环
// let routeFlag = false;

router.beforeEach(async (to, from, next) => {
  NProgress.start();  // 开始进度条
  if (localStorage.getItem("token")) {
    let storeLi = StoreUsers()
    // 获取用户信息
    await storeLi.getPermission()

    let permissionList = JSON.parse(localStorage.getItem("permissionList") as any)
    // 擦找对应的路由
    let routerLo = routerArray.filter((item) => permissionList?.includes(item.name));
    routerLo.forEach(item => {
      // 动态添加路由
      router.addRoute('/', item)
    })

    console.log(router.getRoutes(), '查看现有路由')
    // router.removeRoute()
    next();
    // // 注册动态路由
    // return registerRoutes().then(() => {
    //   routeFlag = true;
    //   next();
    // }).catch(() => {
    //   // 处理异常事件
    // })
    // }
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next("/login");
    }
  }
});

router.afterEach((to, from, next) => {
  NProgress.done();  // 结束进度条
})

export default router
